/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';

import { pickedModelData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { usePointContext } from './PointContext';

type FormDataType = {
  x: number;
  y: number;
  z: number;
  startPoint?: pickedVertexData;
  frame?: pickedModelData;
};

type ChildLineCommandProps = {
  onClose: VoidFunction;
  props: any;
  editDxid?: string;
};

export function PointAxis({ onClose, props, editDxid }: ChildLineCommandProps) {
  const { picker } = useTools();
  const [formData, setFormData] = useState<FormDataType>({
    x: 0,
    y: 0,
    z: 0,
    startPoint: undefined,
    frame: null,
  });

  const { sharedPoint } = usePointContext();

  // 坐标轴
  // const axisRef = useRef<string>('')

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const axis = props?.params?.point;
      const defaultX = axis ? axis[0] : 0;
      const defaultY = axis ? axis[1] : 0;
      const defaultZ = axis ? axis[2] : 0;
      const origin = props?.params?.origin;
      const frame = props?.params?.frame;

      await initEditDependency([origin, frame]);

      const defaultStartPoint = origin
        ? (picker.generatePickObjByPickID(origin) as pickedVertexData)
        : undefined;
      const defaultFrame = frame
        ? (picker.generatePickObjByPickID(frame) as pickedModelData)
        : undefined;
      setFormData({
        x: defaultX,
        y: defaultY,
        z: defaultZ,
        startPoint: defaultStartPoint,
        frame: defaultFrame,
      });
    } else {
      if (sharedPoint) {
        setFormData({
          x: sharedPoint[0],
          y: sharedPoint[1],
          z: sharedPoint[2],
          startPoint: undefined,
          frame: null,
        });
      }
    }
  }, [editDxid]);

  const checkAndFinishDraw = async () => {
    const { x, y, z, startPoint } = formData;
    if (x == null || y == null || z == null) {
      return;
    }

    const origin = startPoint?.vertexId;
    if (props && origin === props?.shape) {
      MessageTip.error('参考点不能为编辑点自身');
      return;
    }

    execute(false);
    onClose();
  };

  const isFormDataValid = () => {
    const { x, y, z } = formData;
    return x != null && y != null && z != null;
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-point', {
      commandName: 'CreateVertex',
      editDxid: editDxid || props?.shape,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = async (preview: boolean) => {
    const { x, y, z, startPoint, frame } = formData;
    const params = {
      mode: 'coordinate',
      point: [x, y, z],
      origin: getIdOfPickedObj(startPoint),
      frame: getIdOfPickedObj(frame),
    };

    await confirmCommand(
      {
        a: params,
      },
      preview,
    );
  };

  const preview = async () => {
    const { x, y, z } = formData;
    clear();

    if (x == null || y == null || z == null) {
      return;
    }

    await execute(true);
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      x: {
        type: 'number',
        title: 'X坐标',
        default: 0,
        format: NumberInputFormat.Length,
      },
      y: {
        type: 'number',
        title: 'Y坐标',
        default: 0,
        format: NumberInputFormat.Length,
      },
      z: {
        type: 'number',
        title: 'Z坐标',
        default: 0,
        format: NumberInputFormat.Length,
      },
      startPoint: {
        type: 'string',
        title: '参考点',
        format: PickInputRJSFFormat.PickVertex,
      },
      frame: {
        title: '参考系',
        type: 'string',
        format: PickInputRJSFFormat.PickFrame,
      },
    },
  };

  const extraUiSchema = {
    x: {
      'ui:placeholder': '请输入x坐标',
      'ui:autofocus': true,
    },
    y: {
      'ui:placeholder': '请输入y坐标',
    },
    z: {
      'ui:placeholder': '请输入z坐标',
    },
    startPoint: {
      'ui:placeholder': '参考点(默认初始原点)',
    },
    frame: {
      'ui:placeholder': '参考系(默认初始轴系)',
    },
  };

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      className='-mt-3'
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        const data = {
          x: v.x,
          y: v.y,
          z: v.z,
          startPoint: !isEmpty(v.startPoint) ? v.startPoint : undefined,
          frame: v.frame,
        };
        setFormData(data);
      }}
      extraUiSchema={extraUiSchema}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
